import { Component, OnInit,Output,EventEmitter, Input} from '@angular/core';
import { FormControl } from '@angular/forms';
import { CudTableService } from '../../../../public/serve/cud-table/cud-table.service';
import { SynonymItems } from './synonym.data';
import { keyword } from '../../../keyword.data';
import { appKeywordUrl } from '../../../keyword.url';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { MatAutocompleteSelectedEvent } from '@angular/material';
import { Service } from '../../../../server/server';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-trial-synonym-autocomplate',
  templateUrl: './trial-synonym-autocomplate.component.html',
  styleUrls: ['./trial-synonym-autocomplate.component.css']
})
export class TrialSynonymAutocomplateComponent implements OnInit {

    myControl = new FormControl();
    @Output() onSubmit = new EventEmitter<void>();
    options: any[] = [];
    filteredOptions: Observable<string[]>;
    public currentValue : any;
    public synonymThemeWordsId : any;
    @Input() themeWordsId;

    constructor(
        public request: CudTableService,
        private hintsService: HintsService,
        private server: Service
    ) { }

    ngOnInit() {
        this.myControl.valueChanges.subscribe(data=>{
            this.currentValue = null;
            this._filter();
        });
    }

    _filter(){
        let tmpValue = this.myControl.value;
        
        let filterValue = '';
        if(tmpValue != ''&& Object.prototype.toString.call(tmpValue) !== '[object Object]'){
            if(Object.prototype.toString.call(tmpValue) === '[object Object]'){
                filterValue = tmpValue['txt'];
                this.synonymThemeWordsId = tmpValue['val'];
            }else{
                filterValue = tmpValue;
            }
            this.getThemeWordsByIndex(filterValue);
        }else{
            this.options = [];
        }
    }

    //回车事件,新增同义词组
    _selectValue(){
        if(Object.prototype.toString.call(this.currentValue) === '[object Object]'){
            //新增同义词组
            //this.addSynonymGroup(this.currentValue.val);
        }else{
            //不存在的主题词
            this.hintsService.messages('请输入主题词名称','9999');
        }
    }

    //选择事件
    onSelectionChanged(event: MatAutocompleteSelectedEvent) {
        this.currentValue = event['value'];

        //新增同义词组
        this.addSynonymGroup(this.currentValue.val);
    }

    displayFn(items: SynonymItems): any {
        return items ? items.txt : items;
    }

    //获取主题词列表
    getThemeWordsByIndex(filterValue){
        let data = {
            token: keyword.retrieval.token,
            pageNo        : 1,
            pageSize      : 20,
            queryCriteria : filterValue,
        };
        
        let url = this.server.baseUrl + appKeywordUrl.getThemeWordsList;
        this.request.postRequest(url,data).then((res:any) => {
            this.options = [];
            if (res.result_code === '0000') {
                res.result.forEach((item, index)=>{
                    this.options.push({
                        'txt':item.name,
                        'val':item.themeWordsId
                    });
                });
            }else{
                this.hintsService.messages(res.message,res.result_code);
            }
        })
        .catch((err: any)=>{
            this.hintsService.messages("error","error");
            return;
        });
    }

    /**
     * 新增同义词组
     */
    addSynonymGroup(synonymThemeWordsId){
        let data = {
            token: keyword.retrieval.token,
            themeWordsId        : this.themeWordsId,
            synonymThemeWordsId : synonymThemeWordsId
        };

        let url = this.server.baseUrl + appKeywordUrl.addSynonymGroup;
        this.request.postRequest(url,data).then((res:any) => {
            this.options = [];
            if (res.result_code === '0000') {
               this.onSubmit.emit();
            }

            this.hintsService.messages(res.message,res.result_code);
        })
        .catch((err: any)=>{
            this.hintsService.messages("error","error");
            return;
        });
    }

}
